package com.liuzh.websocket.dao;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;

@SuppressWarnings("rawtypes")
public class SQLService{

	@Autowired
	protected Dao dao;

	private String sql = null;

	public String getSql(String sqlkey){

		return getXml(sqlkey, getSqlPath());

	}
	public String getSql(String sqlKey, Map<String, Object> params){

		String sql = getSql(sqlKey);

		for (String key : params.keySet()){

			sql = sql.replaceAll(key,String.valueOf(params.get(key)));

		}

		return sql;
	}

	/**
	 * 获取sql文件路径
	 * @return
	 */
	private String getSqlPath(){

		SQLFile anno = this.getClass().getAnnotation(SQLFile.class);
		//当前class所在文件夹下
		String classpath = this.getClass().getResource("/").getPath();

		String realePath = classpath + anno.value();

		return realePath;
	}

	/**
	 * 获取sql语句
	 * @param ele
	 * @param sqlkey
	 * @return
	 */
	private String getSqlString(Element ele,String sqlkey){
			
		List list = ele.elements();
		
		for (int i = 0; i < list.size(); i++) {
			
			Element ele2 = (Element) list.get(i);
			
			if( ele2.elements().size() > 0 ){
				
				sql = getSqlString(ele2, sqlkey);	
				
			}else if( sql == null ){
				
				if( sqlkey.equals(ele2.getName()) ){
					
					return ele2.getText().trim();
					
				}
				
			}
			
		}
		
		return sql;
		
	}

	/**
	 * 获取sql文件根节点对象
	 * @param sqlkey
	 * @param path
	 * @return
	 */
	private String getXml(String sqlkey, String path){
		
		Document document = null;
		
		SAXReader saxReader = new SAXReader();
		
		File file = new File(path);
		
		try {
			
			document = saxReader.read(file);
			
			Element root = document.getRootElement();
			
			return getSqlString(root, sqlkey);
			
		} catch (Exception e) {
			
			e.printStackTrace();
			
		}
		
		return null;
		
	}


}
